package com.wyh.service.serviceImpl.gfiveImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyh.common.result.Result;
import com.wyh.domain.dto.gfive.RoleAddDTO;
import com.wyh.domain.dto.gfive.RoleUpdateDTO;
import com.wyh.domain.po.gfive.*;
import com.wyh.mapper.gfivemapper.PermissionsMapper;
import com.wyh.mapper.gfivemapper.RoleMapper;
import com.wyh.mapper.gfivemapper.RolePermissionsMapper;
import com.wyh.service.gfive.RoleService;
import com.wyh.service.gfive.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author KmJHHhhhR
 * @description 针对表【role(角色表)】的数据库操作Service实现
 * @createDate 2024-05-20 15:03:04
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Resource
    private RolePermissionsMapper rolePermissionsMapper;

    @Resource
    private PermissionsMapper permissionsMapper;

    @Resource
    private UserRoleService userRoleService;




    @Override
    public Result<Map<String, Object>> selectRole(String name, Integer state, PageHelper pageHelper) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (state != null) {
            queryWrapper.eq("state", state);
        }
        List<Role> roles = roleMapper.selectList(queryWrapper);
        if (roles.size() == 0) {
            return Result.error();
        }

        Page<Role> page = new Page<Role>(pageHelper.getCurrentPage(), pageHelper.getPageSize());
        IPage<Role> roleIPage = roleMapper.selectPage(page, queryWrapper);

        if (roleIPage.getRecords().size() == 0) {
            return Result.error();
        }

        Map<String, Object> resultData = new HashMap<>();
        resultData.put("records", roleIPage.getRecords());
        resultData.put("current", roleIPage.getCurrent());
        resultData.put("pages", roleIPage.getPages());
        resultData.put("total", roleIPage.getTotal());

        return Result.success(resultData);
    }


    @Override
    @Transactional
    public Result<RoleUpdateDTO> updateRole(RoleUpdateDTO roleUpdateDTO) {

        //获取该角色
        Role role = roleMapper.selectById(roleUpdateDTO.getRoleId());

        if (role == null) {
            throw new RuntimeException("未找到该角色");
        }

        if (roleUpdateDTO.getRoleName() != null) {
            LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Role::getName,roleUpdateDTO.getRoleName());
            List<Role> roleUpdateDTOS = baseMapper.selectList(lambdaQueryWrapper);

            for (Role roleUpdate : roleUpdateDTOS) {
                if (roleUpdate.getName().equals(roleUpdateDTO.getRoleName())) {
                    return Result.error("5001","名称已存在");
                }
            }

            role.setName(roleUpdateDTO.getRoleName());
            roleMapper.updateById(role);
        }

        if (roleUpdateDTO.getPermissionIds() != null) {

            rolePermissionsMapper.delete(
                    new QueryWrapper<RolePermissions>().eq("roleId", roleUpdateDTO.getRoleId())
            );

            for (Integer permissionId : roleUpdateDTO.getPermissionIds()) {
                Permissions permission = permissionsMapper.selectOne(
                        new QueryWrapper<Permissions>().eq("id", permissionId)
                );

                if (permission != null) {
                    RolePermissions rolePermissions = new RolePermissions();
                    rolePermissions.setRoleid(roleUpdateDTO.getRoleId());
                    rolePermissions.setPermissionid(permission.getId());
                    rolePermissionsMapper.insert(rolePermissions);
                }
            }
        }


        return Result.success(roleUpdateDTO);
    }

    @Override
    @Transactional

    public Result updateRoleState(RoleStatusUpdateRequest request) {
        Role role = roleMapper.selectById(request.getRoleId());
        QueryWrapper<RolePermissions> queryWrapper = new QueryWrapper<>();
        List<RolePermissions> rolePermissions = rolePermissionsMapper
                .selectList(queryWrapper.eq("roleId", request.getRoleId()));

        if (role == null) {
            return Result.error("角色未找到");
        }
        if (role.getState() == 0) {
            return Result.error("该角色已停用");
        }
        List<UserRole> userRoles = userRoleService.selectUserRole(request.getRoleId());

        if (userRoles.size() > 0) {
            for (UserRole userRole : userRoles) {
                if (userRole.getState() == 1) {
                    return Result.error("该角色关联用户不能停用");
                }
            }
        }

        role.setState(request.getNewState());
        for (RolePermissions permissions : rolePermissions) {
            permissions.setState(0);
            rolePermissionsMapper.updateById(permissions);
        }

        roleMapper.updateById(role);
        return Result.success(role);
    }


    @Override
    @Transactional
    public Result<RoleAddDTO> addRoleWithPermissions(RoleAddDTO roleAddDTO) {
        // 创建新角色
        Role role = new Role();

        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Role::getName,roleAddDTO.getRoleName());
        List<Role> roleAddDTOS = baseMapper.selectList(lambdaQueryWrapper);

        for (Role roleAdd : roleAddDTOS) {
            if (roleAdd.getName().equals(roleAddDTO.getRoleName())) {
                return Result.error("5001","名称已存在");
            }
        }

        role.setName(roleAddDTO.getRoleName());
        this.save(role);

        // 获取新插入角色的 ID
        Integer roleId = role.getId();

        // 获取每个权限的 ID 并插入 role_permissions 表
        for (Integer permissionId : roleAddDTO.getPermissionIds()) {
            Permissions permission = permissionsMapper.selectOne(
                    new QueryWrapper<Permissions>().eq("id", permissionId)
            );

            if (permission != null) {
                RolePermissions rolePermissions = new RolePermissions();
                rolePermissions.setRoleid(roleId);
                rolePermissions.setPermissionid(permission.getId());
                rolePermissionsMapper.insert(rolePermissions);
            }
        }

        return Result.success(roleAddDTO);
    }

    @Override
    public Result findRolePermission(int roleId){
        QueryWrapper<RolePermissions> queryWrapper = new QueryWrapper<>();
        List<RolePermissions> rolePermissionsList = rolePermissionsMapper.selectList(
                queryWrapper.eq("roleid", roleId)
                        .eq("state", 1));

        // Extracting only the permissionId values
        List<Integer> permissionIds = rolePermissionsList.stream()
                .map(RolePermissions::getPermissionid)
                .collect(Collectors.toList());
        return Result.success(permissionIds);
    }


    @Override
    public List<Role> selectRoleByUserId(Integer id) {
        return roleMapper.selectRoleByUserId(id);
    }

    @Override
    public List<Role> showAllRole() {
        return roleMapper.showAllRole();
    }

    @Override
    public List<String> selectRolesByIds(Integer[] roleIds) {
        return roleMapper.selectRolesByIds(roleIds);
    }
}




